import { isAppendAction } from './'

export const contextMenuEventBus = (modeler) => {
  modeler.on('element.contextmenu', 100, (event) => {
    const { element, originalEvent } = event
    if (!isAppendAction(element)) {
      openPopupMenu(modeler, element, originalEvent, 'replace')
    } else {
      openPopupMenu(modeler, element, originalEvent, 'create')
    }
  })
}

const openPopupMenu = (modeler, element, event, type) => {
  const popupMenu = modeler.get('popupMenu')
  const canvas = modeler.get('canvas')
  if (type === 'replace') {
    if (popupMenu && !popupMenu.isEmpty(element, 'bpmn-replace')) {
      popupMenu.open(
        element,
        'bpmn-replace',
        {
          x: event.clientX + 10,
          y: event.clientY + 10
        },
        {
          title: '更换元素',
          width: 300,
          search: true
        }
      )
    }
  } else {
    const rootElement = canvas.getRootElement()
    const position = {
      x: event.x,
      y: event.y
    }
    popupMenu.open(rootElement, 'bpmn-create', position, {
      title: '创建元素',
      width: 300,
      search: true
    })
  }
  const container = canvas.getContainer()
  const closePopupMenu = () => {
    if (popupMenu && popupMenu.isOpen()) {
      popupMenu.close()
      container.removeEventListener('click', closePopupMenu)
    }
  }
  container.addEventListener('click', closePopupMenu)
}
